<template>
  <div class="form-demo-container">
    <el-card class="demo-card">
      <template #header>
        <div class="card-header">
          <span>Form 组件示例</span>
          <el-button-group>
            <el-button 
              :type="mode === 7 ? 'primary' : ''" 
              size="small"
              @click="switchMode(7)"
            >
              新增模式
            </el-button>
            <el-button 
              :type="mode === 5 ? 'primary' : ''" 
              size="small"
              @click="switchMode(5)"
            >
              编辑模式
            </el-button>
            <el-button 
              :type="mode === 6 ? 'primary' : ''" 
              size="small"
              @click="switchMode(6)"
            >
              查看模式
            </el-button>
          </el-button-group>
        </div>
      </template>

      <!-- Form 组件 -->
      <Form
        ref="formRef"
        :mode="mode"
        :attMap="formData"
        :fldList="fieldList"
        :colNum="2"
        :size="'default'"
        :showPhoto="true"
        :showVideo="true"
        :showAttach="true"
        @field-change="handleFieldChange"
        @photo-selected="handlePhotoSelected"
        @video-selected="handleVideoSelected"
        @attach-selected="handleAttachSelected"
      >
        <!-- 自定义标签插槽示例 -->
        <template #label="{ fld }">
          <span v-if="fld.colname === 'name'" style="color: #f56c6c;">
            {{ fld.namec }}
          </span>
        </template>
      </Form>

      <!-- 操作按钮 -->
      <div class="action-buttons">
        <el-button type="primary" @click="handleSubmit">
          提交表单
        </el-button>
        <el-button @click="handleReset">
          重置表单
        </el-button>
        <el-button @click="handleValidate">
          验证表单
        </el-button>
        <el-button @click="showFormData">
          查看数据
        </el-button>
      </div>
    </el-card>

    <!-- 数据展示 -->
    <el-card class="data-card" v-if="showData">
      <template #header>
        <span>表单数据</span>
      </template>
      <pre>{{ JSON.stringify(formData, null, 2) }}</pre>
    </el-card>
  </div>
</template>

<script>
import Form from '../cx-form/Form.vue'

export default {
  name: 'FormDemo',
  
  components: {
    Form
  },
  
  data() {
    return {
      mode: 7, // 7-新增, 5-编辑, 6-查看
      showData: false,
      
      // 表单数据
      formData: {
        name: '',
        age: '',
        gender: '',
        email: '',
        phone: '',
        address: '',
        birthday: '',
        hobby: '',
        description: '',
        status: '1'
      },
      
      // 字段配置列表
      fieldList: [
        {
          colname: 'name',
          namec: '姓名',
          disptype: 1, // 文本框
          disporder: 1,
          nullable: 0, // 必填
          editable: true,
          tabname: 'demo_table',
          value: ''
        },
        {
          colname: 'age',
          namec: '年龄',
          disptype: 1,
          disporder: 2,
          nullable: 1,
          editable: true,
          tabname: 'demo_table',
          value: ''
        },
        {
          colname: 'gender',
          namec: '性别',
          disptype: 3, // 下拉选择
          disporder: 3,
          nullable: 0,
          editable: true,
          tabname: 'demo_table',
          value: '',
          options: [
            { value: '1', text: '男' },
            { value: '2', text: '女' }
          ]
        },
        {
          colname: 'email',
          namec: '邮箱',
          disptype: 1,
          disporder: 4,
          nullable: 1,
          editable: true,
          tabname: 'demo_table',
          value: ''
        },
        {
          colname: 'phone',
          namec: '手机号',
          disptype: 1,
          disporder: 5,
          nullable: 1,
          editable: true,
          tabname: 'demo_table',
          value: ''
        },
        {
          colname: 'birthday',
          namec: '生日',
          disptype: 11, // 日期选择
          disporder: 6,
          nullable: 1,
          editable: true,
          tabname: 'demo_table',
          value: ''
        },
        {
          colname: 'hobby',
          namec: '爱好',
          disptype: 6, // 多选
          disporder: 7,
          nullable: 1,
          editable: true,
          tabname: 'demo_table',
          value: '',
          options: [
            { value: '1', text: '读书' },
            { value: '2', text: '运动' },
            { value: '3', text: '音乐' },
            { value: '4', text: '旅游' }
          ]
        },
        {
          colname: 'status',
          namec: '状态',
          disptype: 8, // 开关
          disporder: 8,
          nullable: 1,
          editable: true,
          tabname: 'demo_table',
          value: '1',
          options: [
            { value: '0', text: '禁用' },
            { value: '1', text: '启用' }
          ]
        },
        {
          colname: 'address',
          namec: '地址',
          disptype: 2, // 文本域
          disporder: 9,
          nullable: 1,
          editable: true,
          tabname: 'demo_table',
          disprows: 3,
          value: ''
        },
        {
          colname: 'description',
          namec: '描述',
          disptype: 2,
          disporder: 10,
          nullable: 1,
          editable: true,
          tabname: 'demo_table',
          disprows: 5,
          value: ''
        }
      ]
    }
  },
  
  created() {
    // 初始化 cx 全局对象（模拟）
    this.initCxGlobal()
    
    // 同步字段值到 formData
    this.syncFieldValues()
  },
  
  methods: {
    /**
     * 初始化 cx 全局对象（模拟）
     */
    initCxGlobal() {
      if (!window.cx) {
        window.cx = {
          consts: {
            DISP_TEXTBOX: 1,      // 文本框
            DISP_RICHTEXT: 2,     // 文本域
            DISP_LIST: 3,         // 下拉选择
            DISP_DROPDOWN: 4,     // 可输入下拉
            DISP_RADIO: 5,        // 单选
            DISP_MULTISEL: 6,     // 多选
            DISP_VALBUTTON: 7,    // 值按钮
            DISP_SWITCH: 8,       // 开关
            DISP_DATE: 11,        // 日期
            DISP_TIMESTAMP: 12,   // 日期时间
            DISP_TIME: 13,        // 时间
            DISP_DATEYEAR: 14,    // 年份
            DISP_SELCOLOR: 15,    // 颜色选择
            ATT_ADD: 7,           // 新增模式
            ATT_EDIT: 5,          // 编辑模式
            ATT_QUERY: 6,         // 查看模式
            TEXT_SEPARATOR: ','
          },
          fld: {
            dispTypeName: (disptype, disprows) => {
              const typeMap = {
                1: 'textbox',
                2: disprows === 1 ? 'textarea-auto' : 'textarea',
                3: 'select',
                4: 'dropdown',
                5: 'radio',
                6: 'multisel',
                7: 'valbutton',
                8: 'switch',
                11: 'date',
                12: 'datetime',
                13: 'time',
                14: 'year',
                15: 'color'
              }
              return typeMap[disptype] || 'textbox'
            }
          },
          fldvalue: {
            queryFldValueListAuto: async ({ tabname, colname }) => {
              // 模拟返回字段值列表
              const field = this.fieldList.find(f => f.colname === colname)
              return field?.options || []
            }
          }
        }
      }
    },
    
    /**
     * 同步字段值
     */
    syncFieldValues() {
      this.fieldList.forEach(field => {
        if (this.formData[field.colname] !== undefined) {
          field.value = this.formData[field.colname]
        }
      })
    },
    
    /**
     * 切换模式
     */
    switchMode(newMode) {
      this.mode = newMode
      
      // 根据模式更新字段可编辑状态
      this.fieldList.forEach(field => {
        field.editable = newMode !== 6
      })
    },
    
    /**
     * 字段变化处理
     */
    handleFieldChange(data) {
      console.log('字段变化:', data)
      
      // 同步字段值到 formData
      this.fieldList.forEach(field => {
        this.formData[field.colname] = field.value
      })
    },
    
    /**
     * 照片选择处理
     */
    handlePhotoSelected(photo) {
      console.log('照片选择:', photo)
      this.$message.success('照片已选择')
    },
    
    /**
     * 视频选择处理
     */
    handleVideoSelected(video) {
      console.log('视频选择:', video)
      this.$message.success('视频已选择')
    },
    
    /**
     * 附件选择处理
     */
    handleAttachSelected(attach) {
      console.log('附件选择:', attach)
      this.$message.success('附件已选择')
    },
    
    /**
     * 提交表单
     */
    async handleSubmit() {
      try {
        // 验证表单
        const valid = await this.$refs.formRef.validate()
        
        if (valid) {
          console.log('表单数据:', this.formData)
          this.$message.success('表单提交成功')
        }
      } catch (error) {
        console.error('表单验证失败:', error)
        this.$message.error('表单验证失败，请检查必填项')
      }
    },
    
    /**
     * 重置表单
     */
    handleReset() {
      Object.keys(this.formData).forEach(key => {
        this.formData[key] = ''
      })
      
      this.fieldList.forEach(field => {
        field.value = ''
      })
      
      this.$message.info('表单已重置')
    },
    
    /**
     * 验证表单
     */
    async handleValidate() {
      try {
        const valid = await this.$refs.formRef.validate()
        
        if (valid) {
          this.$message.success('表单验证通过')
        }
      } catch (error) {
        this.$message.error('表单验证失败')
      }
    },
    
    /**
     * 显示表单数据
     */
    showFormData() {
      this.showData = !this.showData
    }
  }
}
</script>

<style lang="scss" scoped>
.form-demo-container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.demo-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.action-buttons {
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid #e8e8e8;
  text-align: center;
}

.data-card {
  pre {
    background: #f5f7fa;
    padding: 15px;
    border-radius: 4px;
    overflow-x: auto;
  }
}
</style>
